#!usr/bin/env python
#coding=utf8

from __future__ import with_statement

import re
import os
from PIL import Image
import uuid
from tuangou import config

if os.name == 'nt':
    FolderExistsError = (WindowsError, OSError)
    FolderExistsCode = (183, 17)
elif os.name == 'posix':
    FolderExistsError = (OSError,)
    FolderExistsCode = (17,)


def get_page_offset(page, page_size):
    '''
    获取分页偏移行数
    @param page: 从1开始算的页码
    @param page_size: 分页大小
    '''
    if not page:
        page = 1
    else:
        try:
            page = int(page)
        except:
            page = 1
    if page < 1:
        page = 1
    if not page_size:
        page_size = 10
    else:
        try:
            page_size = int(page_size)
        except:
            page_size = 10
    #if page_size < 5:
    #    page_size = 5
    return page, page_size, (page-1) * page_size
    

def get_value_from_request(method, request, argv, code=None):
    '''从request或者response对象中根据method方法获取argv指定的值
        @param req: request对象
        @param argv: 列表参数或者设定默认值的字典
        @param method:request方法，如：get,post,files, cookies等等
    return <type 'dict'>
    '''
    r_dic = {}
    method_switch = {'get' : 'GET', 'post' : 'POST', 'files' : 'FILES', 'cookies' : 'COOKIES', 'meta' : 'META'}
    rMet = method_switch[method.lower()] if method.lower() in method_switch.keys() else None
    if rMet is not None:
        if isinstance(argv, dict):
            for i in argv:
                argv[i] = getattr(request, rMet).get(i, '')
            r_dic = argv
        else:
            if argv:
                if isinstance(argv, tuple) or isinstance(argv, list):
                    for i in argv:
                        r_dic[i] = getattr(request, rMet).get(i, '')
            else:
                in_argv_ls = getattr(request, rMet).items()
                r_dic = dict(in_argv_ls)
        for i in r_dic:
            if r_dic[i]:
                r_dic[i] = r_dic[i].strip() 
    if code:
        v_ls = [[i.encode(code), r_dic[i].encode(code)] for i in r_dic if r_dic[i]]
        r_dic = dict(v_ls)
    return r_dic

def get_form_error_msg(form):
    err_msg = ''
    for k,v in form.errors.items():
        err_msg = err_msg + k + ': ' + v.as_text() + '; '
    return err_msg
    
def split_tag_list(taglist):
    tags = re.split(u'[;,；，]', taglist)
    return tags

def get_order_by(order_by):
    result = order_by
    if order_by[0:1] == '-':
        result = order_by[1:len(order_by)] + ' DESC '
        
    return result
####
#    文件操作
#################

def ensure_dir_exist(dirPath):
    if not os.path.exists(dirPath):
        try:
            os.makedirs(dirPath)
        except FolderExistsError, e:
            if not e.args[0] in FolderExistsCode:
                raise

def write_file(file_path, file_content, m = "wb", fp=None):
    if fp:
        fp.write(file_content)
    else:
        ensure_dir_exist(os.path.dirname(file_path))
        with file(file_path, m) as f:
            f.write(file_content)
            
REMOVE_HTMLTAG_RE = re.compile(ur'(<.*?>)', re.I)
def remove_html(v):
    """移除所有html"""
    return REMOVE_HTMLTAG_RE.sub(u'', v).strip()


def decimalFormat(value):
    import decimal
    return decimal.Decimal(value).quantize(decimal.Decimal('0.01'))

def save_item_image(file):
    p, ext = os.path.splitext(file.name)
    #savePath = config.STATIC_PATH + "\\productimgs\\"
    savePath = os.path.join(config.STATIC_PATH, 'productimgs')
    thumb350 = str(uuid.uuid1()) + ext
    thumb800 = str(uuid.uuid1()) + ext
    image = Image.open(file)
    image.thumbnail((800,800),Image.ANTIALIAS)  
    image.save(os.path.join(savePath, thumb800))
    image.thumbnail((350,350),Image.ANTIALIAS)  
    image.save(os.path.join(savePath, thumb350))
    return thumb350, thumb800

    